package com.li.stack;

import java.lang.reflect.Array;
import java.util.Scanner;

public class ArrayStackdemo1 {
    public static void main(String[] args) {
        Arraystack arraystack = new Arraystack(4);
        String key = "";
        boolean loop = true;
        Scanner scanner = new Scanner(System.in);
        while (loop) {
            System.out.println("show,显示全栈");
            System.out.println("exit,退出程序");
            System.out.println("push入栈");
            System.out.println("pop出战");
            key = scanner.next();
            switch (key) {
                case "show":
                    arraystack.list();
                    break;
                case "push":
                    System.out.println("输入一个数");
                    int value = scanner.nextInt();
                    arraystack.push(value);
                    break;
                case "pop":
                    try {
                        int res = arraystack.pop();
                        System.out.println("出栈为" + res);
                    } catch (Exception e) {
                        System.out.println(e.getMessage());
                    }
                    break;
                case "exit":
                    scanner.close();
                    loop = false;
                    break;
            }
        }
        System.out.println("程序退出");
    }

}

class Arraystack {
    private int maxSize;
    private int[] stack;
    private int top = -1;

    public Arraystack(int maxSize) {
        this.maxSize = maxSize;
        stack = new int[this.maxSize];
    }

    public boolean isfull() {
        return top == maxSize - 1;
    }

    public boolean isempty() {
        return top == -1;
    }

    public void push(int value) {
        if (isfull()) {
            System.out.println("堆满");
            return;
        } else {
            top++;
            stack[top] = value;
        }

    }

    //出栈
    public int pop() {
        if (isempty()) {
            throw new RuntimeException("没有数据");
        }
        int value = stack[top];
        top--;
        return value;
    }

    public void list() {
        if (isempty()) {
            throw new RuntimeException("没有数据");
        }
        for (int i = top; i >= 0; i--) {
            System.out.printf("stack[%d]%d", i, stack[i]);
        }
    }
}
